package com.aabte.auth.role.domain.model;

import com.aabte.auth.group.domain.model.Group;
import com.aabte.auth.shared.model.BaseModelUseLongPK;
import com.aabte.commons.ddd.shared.DomainEntity;
import lombok.Getter;
import lombok.ToString;

import javax.persistence.*;
import java.util.Objects;
import java.util.Set;

import static javax.persistence.ConstraintMode.NO_CONSTRAINT;

@SuppressWarnings("all")
@Entity
@Table(name = "tb_role")
@Getter
@ToString(callSuper = true)
public class Role extends BaseModelUseLongPK implements DomainEntity<Role, RoleId> {

    @Embedded
    private RoleId roleId;

    @Embedded
    private RoleName roleName;

    @Enumerated(value = EnumType.ORDINAL)
    private Status status;

    @ManyToMany
    @JoinTable(name = "tb_group_role", joinColumns = {
            @JoinColumn(name = "role_pk", foreignKey = @ForeignKey(NO_CONSTRAINT))
    }, inverseJoinColumns = {
            @JoinColumn(name = "group_pk", foreignKey = @ForeignKey(NO_CONSTRAINT))
    })
    private Set<Group> groups;

    private Role() {
    }

    public Role(RoleId roleId, RoleName roleName) {
        this(roleId, roleName, Status.ENABLE);
    }

    public Role(RoleId roleId, RoleName roleName, Status status) {
        this.roleId = roleId;
        this.roleName = roleName;
        this.status = status;
    }

    @Override
    public boolean sameIdentityAs(Role role) {
        return this.roleId.equals(role.roleId);
    }

    @Override
    public RoleId identity() {
        return this.roleId;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Role role = (Role) o;
        return roleId.equals(role.roleId);
    }

    @Override
    public int hashCode() {
        return Objects.hash(roleId);
    }

    public void disable() {
        this.status = Status.DISABLE;
    }
}
